const Question = require('../models/Question')

class QuestionCtl {
  /**
   * 问题列表
   * @param {Object} ctx 
   */
  async find(ctx) {
    const { per_page = 3 } = ctx.query
    const page = Math.max(ctx.query.page * 1, 1) - 1
    const perPage = Math.max(per_page * 1, 1)
    const q = new RegExp(ctx.query.q)
    ctx.body = await Question
      .find({ $or: [{ title: q }, { description: q }] })
      .limit(perPage).skip(page * perPage)
  }
  /**
   * 检查这个问题是否存在
   * @param {Object} ctx 
   * @param {Object} next 
   */
  async checkQuestionExist(ctx, next) {
    const question = await Question.findById(ctx.params.id).select('+questioner')
    if (!question) {
      ctx.throw(404, '问题不存在')
    }
    ctx.state.question = question
    await next()
  }
  /**
   * 获取某个特定的问题
   * @param {Object} ctx 
   * (问题下的话题)
   */
  async findById(ctx) {
    const { filelds = '' } = ctx.query
    console.log(filelds)
    const selectFields = filelds.split(';').filter(f => f).map(f => ' +' + f).join('')
    const question = await Question.findById(ctx.params.id).select(selectFields).populate('questioner topics')
    ctx.body = question
  }
  /**
   * 创建问题
   * @param {Object} ctx 
   */
  async create(ctx) {
    ctx.verifyParams({
      title: { type: 'string', required: true },
      description: { type: 'string', required: false },
      questioner: { type: 'string', required: false }
    })
    console.log(ctx.request.body)
    const question = await new Question({ ...ctx.request.body, questioner: ctx.state.user._id }).save()
    ctx.body = question
  }
  /**
   * 检查用户是否该问题提问者
   * @param {Object} ctx 
   * @param {Object} next 
   */
  async checkQuestioner(ctx, next) {
    const { question } = ctx.state
    if (question.questioner.toString() !== ctx.state.user._id) {
      ctx.throw(403, '没有更改权限')
    }
    await next()
  }
  /**
   * 修改问题信息
   * @param {Object} ctx 
   */
  async update(ctx) {
    ctx.verifyParams({
      name: { type: 'string', required: false },
      description: { type: 'string', required: false },
      questioner: { type: 'string', required: false }
    })
    await ctx.state.question.update(ctx.request.body)
    ctx.body = ctx.state.question
  }
  /**
   * 删除问题
   * @param {Object} ctx 
   */
  async delete(ctx) {
    await Question.findByIdAndRemove(ctx.params.id)
    ctx.status = 204
  }
}

module.exports = new QuestionCtl()